package syncStory

import (
	"database/sql"
	"encoding/json"
	"log"
	"path"
	"sync"

	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/store"
	"smartconn.cc/tosone/ra_main/taskMgr"
)

const serviceName = "uncompress"

var err error

var stoppedChan chan bool // 内部的停止事件通知信道

var running = false

func init() {
	var locker, stoplocker sync.Mutex
	var channel chan common.ServiceCommand
	var outterStoppedChannel chan bool // 向外发布停止动作完成

	taskMgr.Register(serviceName, channel)
	go func() {
		for {
			select {
			case control := <-channel:
				switch control.Cmd {
				case "start":
					locker.Lock()
					running = true
					syncStory()
					locker.Unlock()
				case "stop":
					stoplocker.Lock()
					outterStoppedChannel = control.Channel
					if running {
						running = false
					} else {
						stoplocker.Unlock()
						outterStoppedChannel <- true
					}
				}
			case <-stoppedChan:
				stoplocker.Unlock()
				outterStoppedChannel <- true
			}
		}
	}()
}

func syncStory() {
	id, taskContent, err := store.GetATask("syncStory")
	if err != nil {
		log.Println(err)
		return
	}
	var content common.TaskContentSync
	err = json.Unmarshal([]byte(taskContent), &content)
	if err != nil {
		log.Println(err)
		return
	}
	db, err := sql.Open("sqlite3", path.Join(content.Path, "story.db"))
	defer db.Close()
	if err != nil {
		log.Println(err)
		return
	}
	rows, err := db.Query("SELECT * FROM \"pages\"")
	var PageID string
	var feature, manifest []byte
	var num int
	for rows.Next() {
		if !running {
			stoppedChan <- true
			return
		}
		rows.Scan(&PageID, &num, &feature, &manifest)
		log.Println(PageID, num, feature, manifest)
	}
	defer rows.Close()
	store.RemoveTask(id)
}
